package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.CreditAccDetail;
import com.turing.post.organization.util.CreditAccDetailDao;
import com.turing.post.organization.util.IssueBranch;
import com.turing.post.organization.util.IssueBranchBusiness;
import com.turing.post.organization.util.IssueBranchDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.OrganApplicationException;
import com.turing.post.organization.util.OrganRespCode;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.organization.util.SysBranchSubord;
import com.turing.post.organization.util.SysBranchSubordDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * @author zxp
 * @Dec 18, 2012
 */
@Stateless(mappedName = "organization.impl.IssueBranchBusinessImpl")
@Remote
@Local
public class IssueBranchBusinessImpl implements IssueBranchBusiness {

	@EJB(mappedName = "organization.impl.IssueBranchDaoImpl")
	private IssueBranchDao issueBranchDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao sysBranchDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchSubordDaoImpl")
	private SysBranchSubordDao sysBranchSubordDaoImpl;

	@EJB(mappedName = "organization.impl.CreditAccDetailDaoImpl")
	private CreditAccDetailDao creditAccDetailDaoImpl;

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	@Override
	public void insertIssueBranchInfo(PCPSWebInput webInput,
			IssueBranch issueBranch) throws PCPSApplicationException {
		// // 登录用户机构号为空
		// if (PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
		// throw new OrganApplicationException(
		// OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
		// OrganRespCode.ISSUE_INSERT_UPDATE, "登录用户机构号为NULL");
		// }
		// 业务检查
		if (issueBranch == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"IssueBranch");
		}
		// 编号
		if (PCPSUtil.isEmpty(issueBranch.getIssueBranchNo())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"IssueBranchNo");
		}
		// 发卡商机构名称
		if (PCPSUtil.isEmpty(issueBranch.getIssueBranchName())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL,
					"IssueBranchName");
		}
		// 验证发卡商机构号是否已经使用
		if (issueBranchDaoImpl.getIssueBranchByIssueBranchNo(issueBranch
				.getIssueBranchNo()) != null) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.BRANCHNO_EXIST);
		}

		// // 不为超级管理员
		// if
		// (!Config.SUPER_SYSOPUER_BRANCHNO.equals(webInput.getOperBranchNo()))
		// {
		// int length = webInput.getOperBranchNo().length();
		// // 验证登录用户是否归属为当前发卡商
		// if (!webInput.getOperBranchNo().equals(
		// issueBranch.getIssueBranchNo().substring(0, length))) {
		// throw new OrganApplicationException(
		// OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
		// OrganRespCode.ISSUE_INSERT_UPDATE, "无权添加其他发卡商分支机构!");
		// }
		// }

		// 插入平台机构主键表数据
		SysBranch sysBranch = new SysBranch(issueBranch.getIssueBranchNo(),
				SysBranch.SYSBRANCH_ISSUEBRANCH);
		sysBranchDaoImpl.insertSysBranch(sysBranch);
		// 结构树数据
		String issueCompanyNo = issueBranch.getIssueCompanyNo();
		String issueBranchNo = issueBranch.getIssueBranchNo();
		String superIssueBranchNo = issueBranch.getSuperIssueBranchNo();
		// 插入发卡商分支机构
		issueBranchDaoImpl.insertIssueBranch(issueBranch);
		// 发卡商分支机构============
		SysBranchSubord sysBranchSub = null;
		if (!PCPSUtil.isEmpty(issueCompanyNo)) {// 直接隶属于发卡商下
			// 平台机构隶属关系
			// 添加归属发卡商下一级发卡商机构
			sysBranchSub = new SysBranchSubord();
			sysBranchSub.setBranchNo(issueCompanyNo);// 发卡商编号
			sysBranchSub.setSubBranchNo(issueBranchNo);
			sysBranchSub.setSubBranchType(SysBranch.SYSBRANCH_ISSUEBRANCH);
			sysBranchSub.setSubBranchSuperNo(issueCompanyNo);
			sysBranchSubordDaoImpl.insertSysBranchSubord(sysBranchSub);
			// 自己添加自己
			sysBranchSub = new SysBranchSubord();
			sysBranchSub.setBranchNo(issueBranchNo);
			sysBranchSub.setSubBranchNo(issueBranchNo);
			sysBranchSub.setSubBranchType(SysBranch.SYSBRANCH_ISSUEBRANCH);
			sysBranchSubordDaoImpl.insertSysBranchSubord(sysBranchSub);
		}
		if (!PCPSUtil.isEmpty(superIssueBranchNo)) {// 归属于发卡商分支机构
			// 平台机构隶属关系
			List<SysBranchSubord> sysBranchSubordList = sysBranchSubordDaoImpl
					.getSysBranchSubordListBySubBranchNo(superIssueBranchNo);
			// 插入所有父节点对应关系
			SysBranchSubord sbs = null;
			SysBranchSubord _sbs = null;
			for (int i = 0; i < sysBranchSubordList.size(); i++) {
				_sbs = sysBranchSubordList.get(i);
				sbs = new SysBranchSubord();
				sbs.setBranchNo(_sbs.getBranchNo());// 机构号
				sbs.setSubBranchNo(issueBranchNo);// 添加机构机构号
				sbs.setSubBranchType(_sbs.getSubBranchType());// 子机构类型
				sbs.setSubBranchSuperNo(superIssueBranchNo);// 上级机构号
				sysBranchSubordDaoImpl.insertSysBranchSubord(sbs);
			}
			// 自己添加自己
			sysBranchSub = new SysBranchSubord();
			sysBranchSub.setBranchNo(issueBranchNo);
			sysBranchSub.setSubBranchNo(issueBranchNo);
			sysBranchSub.setSubBranchType(SysBranch.SYSBRANCH_ISSUEBRANCH);
			sysBranchSubordDaoImpl.insertSysBranchSubord(sysBranchSub);
		}
		// 插入数据库操作日志
		insertRecordingOperationLog(webInput, "创建发卡商机构", issueBranch,
				SysOperLog.operType_Add, "IssueBranchName:"
						+ issueBranch.getIssueBranchName());
	}

	@Override
	public void updateIssueBranchInfo(PCPSWebInput webInput,
			IssueBranch issueBranch) throws PCPSApplicationException {
		// 登录用户机构号为空
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "登录用户机构号为NULL");
		}
		// 验证登录用户是否归属为当前发卡商
		if (!PCPSUtil.getIssueCompanyNo(webInput).equals(
				issueBranch.getIssueBranchNo().substring(0, 6))) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "无权修改其他发卡商分支机构!");
		}

		IssueBranch _issueBranch = issueBranchDaoImpl
				.getIssueBranchByIssueBranchNo(issueBranch.getIssueBranchNo());
		// 对象赋值
		_issueBranch.setIssueBranchName(issueBranch.getIssueBranchName());
		_issueBranch.setStatus(issueBranch.getStatus());
		_issueBranch.setAddress(issueBranch.getAddress());
		_issueBranch.setLinkMan(issueBranch.getLinkMan());
		_issueBranch.setLinkTele(issueBranch.getLinkTele());
		_issueBranch.setAllowActivate(issueBranch.getAllowActivate());

		issueBranchDaoImpl.updateIssueBranch(_issueBranch);
		// 插入数据库操作日志
		insertRecordingOperationLog(webInput, "修改发卡商机构", issueBranch,
				SysOperLog.operType_Edit, "IssueBranchName:"
						+ issueBranch.getIssueBranchName());
	}

	@Override
	public void updateIssueBranchActivateOrCredit(PCPSWebInput webInput,
			IssueBranch issueBranch) throws PCPSApplicationException {
		// 登录用户机构号为空
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "登录用户机构号为NULL");
		}
		// 验证登录用户是否归属为当前发卡商
		if (!PCPSUtil.getIssueCompanyNo(webInput).equals(
				issueBranch.getIssueBranchNo().substring(0, 6))) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "无权修改其他发卡商分支机构!");
		}

		IssueBranch _ib = issueBranchDaoImpl
				.getIssueBranchByIssueBranchNoForUpdate(issueBranch
						.getIssueBranchNo());
		// 激活额度
		if (issueBranch.getActivateBalance().compareTo(BigInteger.ZERO) != 0) {
			activateAccount(_ib.getIssueBranchNo(),
					CreditAccDetail.Give_Ac_Bal, issueBranch
							.getActivateBalance(), null, null, webInput
							.getOperId());
		}
		// 授信额度
		if (issueBranch.getCreditBalance() != null) {
			if (issueBranch.getCreditBalance().compareTo(BigInteger.ZERO) < 0) {
				throw new OrganApplicationException(
						OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
						OrganRespCode.ISSUE_INSERT_UPDATE, "授信额度不可小于0!");
			}
			// 激活额度小于0时授信额度只能加不能减
			if (_ib.getActivateBalance().compareTo(BigInteger.ZERO) < 0) {
				if (issueBranch.getCreditBalance().compareTo(
						_ib.getCreditBalance()) < 0) {
					throw new OrganApplicationException(
							OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
							OrganRespCode.ISSUE_INSERT_UPDATE,
							"激活额度小于0时授信额度阀值不可减少!");
				}
			}
			_ib.setCreditBalance(issueBranch.getCreditBalance());
			issueBranchDaoImpl.updateIssueBranch(_ib);
		}
		// 插入数据库操作日志
		sysOperLogDaoImpl.insertSysOperLogInfo(webInput,
				SysOperLog.operType_Edit, "发卡商分支机构激活授信额度修改", "激活额度"
						+ issueBranch.getActivateBalance() + "授信额度"
						+ issueBranch.getCreditBalance());
	}

	/**
	 * 激活额度记帐
	 * 
	 * @param issueBranchNo
	 * @param tranType
	 * @param amount
	 * @param orderType
	 * @param orderId
	 * @param operId
	 * @throws PCPSApplicationExceptionF
	 */
	public void activateAccount(String issueBranchNo, String tranType,
			BigInteger amount, String orderType, BigInteger orderId,
			BigInteger operId) throws PCPSApplicationException {
		// 应该检查trantype的合法性
		IssueBranch ib = issueBranchDaoImpl
				.getIssueBranchByIssueBranchNoForUpdate(issueBranchNo);
		BigInteger amt = amount;
		if (PCPSUtil.compareObject(tranType, CreditAccDetail.use_Ac_Bal))
			amt = BigInteger.ZERO.subtract(amt);
		else if (PCPSUtil.compareObject(tranType, CreditAccDetail.Give_Ac_Bal)) {
		} else
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "无效的激活额度交易类型!");
		ib.setActivateBalance(ib.getActivateBalance().add(amt));// 应为负数
		if (ib.getActivateBalance().add(ib.getCreditBalance()).compareTo(
				BigInteger.ZERO) < 0) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "激活额度不足!");
		}
		issueBranchDaoImpl.updateIssueBranch(ib);
		// 记帐明细
		IssueCompany ic = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(issueBranchNo.substring(0, 6));
		CreditAccDetail cad = new CreditAccDetail();
		cad.setCreditAccDetailId(commonDaoImpl.getUniqueIntegerKey());
		cad.setIssueBranchNo(ib.getIssueBranchNo());
		cad.setTranDate(ic.getTranDate());
		cad.setTranType(tranType);
		cad.setTranTime(commonDaoImpl.getDatabaseSysTime());
		cad.setAmount(amount);
		cad.setOrderType(orderType);
		cad.setOrderId(orderId);
		cad.setActivateBalance(ib.getActivateBalance());
		cad.setCreditBalance(ib.getCreditBalance());
		cad.setOperId(operId);
		creditAccDetailDaoImpl.insertCreditAccDetail(cad);
	}

	private void insertRecordingOperationLog(PCPSWebInput webInput,
			String logName, IssueBranch obj, String operType,
			String lastFieldName) throws PCPSApplicationException {
		String logRemark = PCPSUtil.RecordingOperationLog(obj, lastFieldName);
		if (!PCPSUtil.isEmpty(logRemark)) {
			// 插入数据库日志
			SysOperLog sysOperLog = new SysOperLog();
			if (webInput != null && webInput.getOperId() != null) {
				sysOperLog.setOperId(webInput.getOperId());
				sysOperLog.setOperType(operType);
				sysOperLog.setLogName(logName);
				if (webInput != null) {
					sysOperLog.setIpAddress(webInput.getIpAddress());
				}
				if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
					sysOperLog.setIssueCompanyNo(webInput.getOperBranchNo()
							.substring(0, 6));
					sysOperLog.setBranchNo(webInput.getOperBranchNo());
				}
				sysOperLog.setRemark(logRemark);
				sysOperLogDaoImpl.insertSysOperLog(sysOperLog);
			}
		}
	}

	@Override
	public void deleteIssueBranchInfo(PCPSWebInput webInput,
			String issueBranchNo) throws PCPSApplicationException {
		issueBranchDaoImpl.deleteIssueBranch(issueBranchNo);
		sysBranchSubordDaoImpl.deleteSysBranchSubord(issueBranchNo);
		sysBranchDaoImpl.deleteSysBranch(issueBranchNo);
	}
}
